
<!-- 低用于发起审批 -->

<template>
	<eui-background type="common" >
		<view class="lowcode-nav-wrap">
			<eui-nav-bar title="发送审批" color="#333"  />
			<eui-search-bar v-if="(state?.appFlows?.length || 0) > 1" ref="searcBarRef" radius="100" placeholder="请输入流程名称筛选" @confirm="handleEnterSearch" @clear="handleClearSearch" />
		</view>
		<view v-if="state?.viewModeMsg">{{ state?.viewModeMsg }}</view>
		<view v-if="!state?.viewModeMsg">
			<view class="flows-wrap" style="max-height: 300rpx;overflow: auto;padding: 0 0;background-color: #fff;">
				<radio-group @change="handleActiveFlowChange">
					<label class="uni-list-cell uni-list-cell-pd" style="display: flex;background-color: #fff;padding: 20rpx 0;border-bottom: 1px solid #ccc;margin: 0 30rpx;" v-for="(rowFlow, index) in (state.appFlowsFilter || state.appFlows)" :key="rowFlow.FlowGuid">
						<view><radio :value="rowFlow.FlowGuid" :checked="rowFlow.FlowGuid === state.activeFlow?.FlowGuid" /></view>
						<view>{{ rowFlow.FlowName }}[{{ rowFlow?.IsMainFlow === "1" ? "主流程" : "副流程" }}]</view>
					</label>
				</radio-group>
			</view>
			<view class="flow-nodes-wrap" :style="{ height: state.scrollHeight + 'px' }" >
				<view class="main-view-bg" style="background-color: #fff;" :style="{height: (state.scrollHeight - 15) + 'px'}">
					<scroll-view scroll-y :style="{height: (state.scrollHeight - 15) + 'px'}" style="padding: 20px 15px;box-sizing: border-box;">
						<eui-steps :options="state.flowNodes" :active="state.activeNodeIdx" type="approve" currentColor="#FF7E00" activeColor="#00AD60" deactiveColor="#CCC">
							<template v-slot:content="scope" style="margin-top: 16rpx;">
								<view class="WTF-666" style="background: #F9FAFC; border-radius: 10rpx;margin-top: 16rpx;" v-if="scope.content">
									<view style="padding: 20rpx; color: #666666;font-size: 13px;">{{ scope.content }}</view>
								</view>
							</template>
						</eui-steps>
					</scroll-view>
				</view>
			</view>
			<view class="lowcode-popup-bottom flex-1 flex">
				<eui-button type="max2" title="取消" singleTag="取消" @buttonClick="handleCancel" ></eui-button>
				<eui-button type="max" title="发送" singleTag="发送" @buttonClick="handleSend" ></eui-button>
			</view>
		</view>
	</eui-background>
</template>

<script setup lang="ts" >
import { ref } from "vue";
import { onLoad, onReady, onShow } from "@dcloudio/uni-app";

import store from "@/store";
import serviceTools from '@/common/service';
import useService from "@/hooks/useService";
import { initRdsDict, getRdsSysConfig } from "@/hooks/init";

import type { DlgSelApproveFlowSendAppInFo, DlgSelApproveFlowSendProps, DlgSelApproveFlowSendState, FlowChartPathNode } from "./interface";
import { EBillApproveStatus, EBillStatus, ECBillApproveStatus, ECBillStatus } from "../MainViews/lowcode/constant";

const props = defineProps<DlgSelApproveFlowSendProps>();
const service = useService({ prefix: "mainApi" });

const state = ref<DlgSelApproveFlowSendState>({ activeNodeIdx: 1 });

const handleEnterSearch = async (proxy?: { value?: string }) => {
	console.log("handleEnterSearch ", proxy?.value);
	const newFlows = state.value.appFlows?.filter(f => f.FlowName.includes(proxy?.value));
	state.value.appFlowsFilter = newFlows;

	if (!newFlows?.length) {
		return handleAfterFetch();
	}
	const activeFlow = newFlows[0];
	state.value.activeFlow = activeFlow;
	await fetchFlowUserAndPath();
};

const handleClearSearch = async (proxy?: { value?: string }) => {
	console.log("handleClearSearch ", proxy?.value);
	const newFlows = state.value.appFlows;
	state.value.appFlowsFilter = undefined;

	if (!newFlows?.length) {
		return handleAfterFetch();
	}
	const activeFlow = newFlows[0];
	state.value.activeFlow = activeFlow;
	await fetchFlowUserAndPath();
};

const handleActiveFlowChange = async (event) => {
	const newActive = state.value?.appFlows?.find(r => r.FlowGuid === event.detail.value);
	state.value.activeFlow = newActive;
	await fetchFlowUserAndPath();
	console.log("handleActiveFlowChange newActive", newActive?.FlowGuid);
};

// const handleCancel = () => uni.navigateBack();
// const handleCancel = () => {
// 	try {
// 		let pages = getCurrentPages(); // 当前页面
// 		let prevPage = pages[pages.length - 2]; // 上一页
// 		prevPage.$vm.$.exposed.RefreshPage();
// 	} catch (e) {
// 	}
// }
const handleCancel = () => uni.navigateBack({ success: () => uni.$emit("RefreshPage", {}) });

const handleSend = async () => {
	const { AppUsers, IsMachineFlowRule, IsCanDirectPass, FlowGuid, ProjectName, NoticType } = state.value.activeFlow || {};
	if (!(IsCanDirectPass && IsMachineFlowRule) && AppUsers?.length === 0) {
		return serviceTools.enjoyShowToast(`请录入有效的审批用户,再发起审批！`);
	}

	const IsNonConformityDirectPass: string = await getRdsSysConfig("不满足审批条件时是否直接审批", props?.mdCName);
	const isDirectPass = AppUsers?.length === 0 && !IsMachineFlowRule && IsNonConformityDirectPass;
	const fetchMethod = isDirectPass ? "SendAppDirectPass" : "SendApprove";

	// if (!isDirectPass) {
	// 	return;
	// }

	const loginInfo = store?.state?.value?.main?.loginInfo;
	const userNo = loginInfo?.sUser, userName = loginInfo?.userName || "";

	uni.showLoading({ title: "正在发送审批，请稍等.....", mask: true});
	const fetchReq = {
		AppUsers: AppUsers,
		BillRealType: props?.mdCName,
		BillType: props?.mdCName,
		BillKey: props?.billKey,
		MdCode: props?.mdCode,
		BillId: props?.billId,
		TempTitle: state.value?.appTitle,
		UserNo: userNo,
		UserName: userName,
		StoreId: loginInfo?.UserStoreId,
		FlowGuid: FlowGuid,
		ProjectName: ProjectName || props?.app || "main",
		NoticType: NoticType,
		AppParam: props?.uniqueKey,
		CFGName: props?.uniqueKey,
	};
	const fetchReqProxy = { ModuleCode: props?.mdCode };
	const fetchRes = await service.request<any, any>("审批处理", fetchMethod, fetchReq, "", "", fetchReqProxy);
	uni?.hideLoading?.();
	if (fetchRes === null) {
		uni.navigateBack({ success: () => uni.$emit("RefreshPage", {}) });
	}
};

const handleAfterFetch = async () => {
	if (!state.value?.appFlows?.length) {
		state.value.viewModeMsg = "抱歉！请先定义审批流程再发起审批";
	}
	if (state.value?.activeFlow) {
		const IsNonConformityDirectPass: string = await getRdsSysConfig("不满足审批条件时是否直接审批", props?.mdCName);
		
		const { IsCanDirectPass, IsMachineFlowRule } = state.value?.activeFlow;
		const appUserCount = state.value?.activeFlow?.AppUsers?.length;
		if (IsCanDirectPass && IsMachineFlowRule) {
			state.value.viewModeMsg =  "单据符合直接通过流程条件，请点击发送按钮";
		} else if (appUserCount === 0 && !IsMachineFlowRule && IsNonConformityDirectPass) {
			state.value.viewModeMsg = "该单据没有符合条件的审批流程，参数设置为可直接审批通过，请点击发送按钮......";
		} else if (appUserCount === 0) {
			state.value.viewModeMsg = "没有符合条件的审批用户，请检查流程设置";
		}

		const activeFlowNodes = state.value?.activeFlow?.AppPaths;
		if (Array.isArray(activeFlowNodes)) {
			// state.value.activeNodeIdx = activeFlowNodes?.length - 1;

			let AppDetail = "";
			const flowNodes = [];
			activeFlowNodes.map((item, idx) => {
				// if (item.AppNodeType === "正在审批") {
				// 	state.value.activeNodeIdx = idx;
				// }
				// if (item.ReplyStatus === "不同意") {
				// 	AppDetail = item.AppDetail || "无审批意见";
				// } else if (item.ReplyStatus=="同意") {
				// 	AppDetail = item.AppDetail || "同意";
				// } else {
				// 	AppDetail = item.AppDetail || "546456";
				// }
				const userInfo = item.Child?.map(u => ({ userName: u.AppUsers, userImg: `http://127.0.0.1:8002/File/DownLoadImage/${u?.AppUsers?.split?.("]")?.[0]?.split?.("[")?.[1]}` }));
				flowNodes.push({
					...item,
					title: idx === 0 ? "" : item.NodeName,
					status: idx === 0 ? "发起审批" : "待处理", //item.AppNodeType,
					time: item.AppDateTime,
					userInfo:userInfo,
					content: AppDetail
				})
			});
			state.value.flowNodes = flowNodes;
		}

		if (state.value?.activeFlow?.TempTitle) {
			state.value.appTitle = state.value?.activeFlow?.TempTitle;
		}
	}

	const rectConf = { navH: 0, flowsH: 0, btmH: 0 };
	uni.createSelectorQuery().select(".lowcode-nav-wrap")?.boundingClientRect(navRect => {
		(rectConf.navH = navRect?.height);
		uni.createSelectorQuery().select(".flows-wrap")?.boundingClientRect(flowRect => {
			(rectConf.flowsH = flowRect?.height);
			uni.createSelectorQuery().select(".lowcode-popup-bottom")?.boundingClientRect(popRect => {
				(rectConf.btmH = popRect?.height);
				state.value.scrollHeight = uni.getSystemInfoSync()?.windowHeight - rectConf.navH - rectConf.flowsH - rectConf.btmH;
			}).exec();
		}).exec();
	}).exec();
	console.log("handleAfterFetch === ", state.value);
};

const fetchFlowUserAndPath = async () => {
	const activeFlow = state.value.activeFlow, fetchReqProxy = { ModuleCode: props?.mdCode };
	const loginInfo = store?.state?.value?.main?.loginInfo;
	const userNo = loginInfo?.sUser, userName = loginInfo?.userName || "";
	const fetchReqUsers = {
		...activeFlow,
		BillKey: props?.billKey,
		BillId: props?.billId,
		UserNo: userNo,
		AppParam: props?.uniqueKey,
		CFGName: props?.uniqueKey,
		ProjectName: props?.app || "main",
	};
	uni.showLoading({ title: "正在获取审批用户，请稍等.....", mask: true});
	const fetchUsersRes = await service.request<any, any>("审批处理", "GetExtFixAppUsers", fetchReqUsers, "", "", fetchReqProxy);
	if (!fetchUsersRes) {
		handleAfterFetch();
		return uni?.hideLoading?.();
	}
	const appPaths: FlowChartPathNode[] = [], { FixUsers,AppTitle, ...other } = fetchUsersRes || {};

	if ((FixUsers || []).length) {
		const fetchReqPaths = { Key: activeFlow?.FlowGuid, Value: props.billKey, Value1: userNo };
		const fetchPathsRes = await service.request<any, any>("审批处理", "GetPreApproveByFlowGuid", fetchReqPaths, "", "", fetchReqProxy);
		const retPaths = fetchPathsRes || [];

		if (retPaths.length) {
			appPaths.splice(0, 1, { IsStartNode: true, NodeName: `[${userNo}]${userName}`, Child: [{ AppUsers: `[${userNo}]` }] });
			const resDataObj: { [key: string]: FlowChartPathNode } = {};
			retPaths?.forEach(i => {
				const iNodeName = (i.NodeId || "") + "ABC" + (i.ApproveNumber || 1) + (i.PreNodeId || "") + (i.NodeName || ""); // ABC 对象并不是完全按照插入顺序来排列的
				if (!resDataObj[iNodeName]) {
					resDataObj[iNodeName] = i;
					return resDataObj[iNodeName].Child = [{ ...i }];
				}
				resDataObj[iNodeName].Child.push({ ...i });
			});
			const userAry = Object.values(resDataObj || {});
			appPaths.splice(1, userAry.length, ...(userAry || []));
		}
	}

	const flow = activeFlow;
	const newFlow = { ...flow, TempTitle: AppTitle, AppPaths: appPaths, AppUsers: FixUsers || [], ...other };
	if (flow) {
		if (state.value.appFlowsFilter) {
			const flowIndex = state.value.appFlowsFilter?.indexOf(flow);
			flowIndex && state.value.appFlowsFilter?.splice(flowIndex, 1, newFlow);	
		} else {
			const flowIndex = state.value.appFlows?.indexOf(flow);
			flowIndex && state.value.appFlows?.splice(flowIndex, 1, newFlow);
		}
	}
	state.value.activeFlow = newFlow;

	uni?.hideLoading?.();
	handleAfterFetch();
};

const fetchData = async () => {
	uni.showLoading({ title: "正在查询审批信息，请稍等.....", mask: true});
	const fetchReq = { BillId: props?.billId, UniqueBillId: props?.billKey, ModuleCode: props?.mdCode };
	const fetchReqProxy = { ModuleCode: props?.mdCode };
	const fetchRes = await service.request<any, DlgSelApproveFlowSendAppInFo>("h5approve", "GetBillAppInFo", fetchReq, "", "", fetchReqProxy);
	uni?.hideLoading?.();
	if (!fetchRes) {
		return handleAfterFetch();
	}

	const newBillStatus = props?.billStatus || EBillStatus.NotApproved;
  const newAppStatus = props?.appStatus || EBillApproveStatus.NotYetApproved;
	const editable = (props?.editableStatus || []).includes(newBillStatus);
	
	if (fetchRes?.AppId > 0) {
		if (fetchRes.AppStatus === EBillApproveStatus.ApprovalProgress && newAppStatus !== EBillApproveStatus.ApprovalProgress && newAppStatus !== ECBillApproveStatus.ApprovalProgress) {
			const appStatusStr1 = await getRdsSysConfig("单据状态", fetchRes.AppStatus) || fetchRes.AppStatus;
			const appStatusStr2 = await getRdsSysConfig("单据审批状态", newAppStatus) || newAppStatus;
			const msg = `单据状态异常：单据状态为[${appStatusStr1}]，单据审批状态为[${appStatusStr2}]，不一致`;
			state.value.viewModeMsg = msg;
		} else {
			const condition1 = (newBillStatus === EBillStatus.NotApproved || newBillStatus === ECBillStatus.NotApproved || editable);
			const condition2 = (newAppStatus === EBillApproveStatus.NotYetApproved || newAppStatus === ECBillApproveStatus.NotYetApproved);
			const appId = (condition1 && condition2) ? 0 : fetchRes.AppId;
			state.value.AppId = appId;
		}
	}

	const fetchBillAppBriefRes = await service.request<any, any>(props?.uniqueKey, "GetBillAppBrief", props?.billKey, "", "", fetchReqProxy);
	fetchBillAppBriefRes && (state.value.appTitle = fetchBillAppBriefRes);
	
	const loginInfo = store?.state?.value?.main?.loginInfo;
	const userNo = loginInfo?.sUser, userName = loginInfo?.userName || "";
	const fetchReqFlows = {
		BillRealType: props?.uniqueKey,
		BillType: props?.uniqueKey,
		IsCanTempApp: false,
		MdCode: props?.mdCode,
		ProjectName: props?.app || "main",
		AppReqUserNo: userNo || "",
		BillId: props?.billId
	};
	uni.showLoading({ title: "正在查询流程定义，请稍等.....", mask: true});
	const fetchFlowsRes = await service.request<any, any>("h5approve", "FetchModuleRunFlows", fetchReqFlows, "", "", fetchReqProxy);
	uni?.hideLoading?.();

	if (!fetchFlowsRes) {
		return handleAfterFetch();
	}
	const flows = fetchFlowsRes?.ReqFixDefInFos || [];
	state.value.appFlows = flows;

	if (!flows?.length) {
		return handleAfterFetch();
	}
	const activeFlow = flows[0];
	state.value.activeFlow = activeFlow;
	await fetchFlowUserAndPath();
};

onLoad(async (proxy) => {
	console.log("onLoad proxy ", proxy, props);
	fetchData();
});

// onShow((proxy) => {
// 	console.log("onShow proxy ", proxy);
// });

// onReady(() => {
// 	console.log("onReady proxy ");
// });
</script>

<style scoped lang="scss">
@import '@/main.scss';
@import "../MainViews/lowcode/index.scss";
</style>
